package com.nulldev.util.web.nTube.pages;

import java.util.List;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.languages.json.uniapi.UniJsonValue;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.YouTubeExtractor.trending.YouTubeTrending;
import com.nulldev.util.web.YouTubeExtractor.trending.YouTubeTrending.TrendingEntry;

public class GetTrendingPage extends HttpPage3 {

	public GetTrendingPage() {
		super("/api/get_trending");
	}

	private static final String JSON_MIME = "application/json; charset=utf-8";

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		try {
			final UniJsonValue output = UniJsonValue.object(2);
			output.add("version", 1.1);
			final List<TrendingEntry> te = YouTubeTrending.getTrending();
			final UniJsonValue items = UniJsonValue.array(te.size());
			for (final TrendingEntry entry : te) {
				final UniJsonValue u = UniJsonValue.object();
				u.add("id", entry.videoID);
				u.add("url", entry.url());
				u.add("title", entry.title);
				u.add("duration", entry.durationText);
				u.add("author_verified", entry.isVerified);
				u.add("author", entry.channelName);
				u.add("channel_id", entry.channelLink);
				u.add("img_url", "https://i.ytimg.com/vi/" + entry.videoID + "/mqdefault.jpg");
				u.add("anim_img_url", entry.animated_img_url);
				items.add(u);
			}
			output.add("items", items);
			return new Response(200, output, output).setCustomMime(JSON_MIME);
		} catch (Exception e) {
			JVM.errorln(e);
			return new Response(503);
		}
	}

}
